# encoding=utf-8_general_ci

import os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

import torndb

from update import update

from config import *

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        if not self.get_secure_cookie('user'):
            self.redirect("/login")
            return

        update()

        username = self.get_secure_cookie("user")

        try:
            db = torndb.Connection(db_host, db_name, user = db_user, password= db_password)
        except:
            return

        user_info = db.get("select * from user where username='"+username+"'")
        status_info = db.query("select * from status where author='"+username+"'")
        status_info.sort(key = lambda statu : statu.stime, reverse = True)
        self.render("main.html", user = user_info, message="", status = status_info)

    def post(self):
        if not self.get_secure_cookie('user'):
            self.redirect("/login")
            return
        
        username = self.get_secure_cookie('user')
        
        message = "no changes"

        change_password = self.get_argument("new_password", "")
        change_nickname = self.get_argument("new_nickname", "")
        change_email = self.get_argument("new_email", "")
        change_phone = self.get_argument("new_phone", "")

        try:
            db = torndb.Connection(db_host, db_name, user = db_user, password= db_password)
        except:
            return

        if change_password != "":
            db.execute("update user set password='"+change_password+"' " + "where username='" + username + "'")
            message = "Changed!"
        
        if change_nickname != "":
            db.execute("update user set nickname='"+change_nickname+"' " + "where username='" + username + "'")
            message = "Changed!"

        if change_email != "":
            db.execute("update user set email='"+change_email+"' " + "where username='" + username + "'")
            message = "Changed!"

        if change_phone != "":
            db.execute("update user set phone='"+change_phone+"' " + "where username='" + username + "'")
            message = "Changed!"

        return

